package com.yyfax.ph.progress.detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.utils.FormatUtils;
import com.yyfax.ph.progress.checkCredit.CheckCreditActivity;
import com.yyfax.ph.progress.supplement.SupplementActivity;
import com.yyfax.ph.web.WebActivity;

import java.util.List;

public class ProgressDetailActivity extends BaseYYFaxActivity implements ProgressDetailPresenter.View {

	private static final String EXTRA_RCMD_ID = "extra_rcmd_id";
	private static final int LOADER_ID = 122;
	@BindView(R.id.status_tv)
	TextView mStatusTv;
	@BindView(R.id.time_tv)
	TextView mTimeTv;
	@BindView(R.id.reason_tv)
	TextView mStatusTipTv;
	@BindView(R.id.custom_name_tv)
	TextView mCustomNameTv;
	@BindView(R.id.applicant_license_tv)
	TextView mApplicantLicenseTv;
	@BindView(R.id.cell_phone_number_tv)
	TextView mCellPhoneNumberTv;
	@BindView(R.id.residential_city_tv)
	TextView mResidentialCityTv;
	@BindView(R.id.type_of_job_tv)
	TextView mTypeOfJobTv;
	@BindView(R.id.company_name_tv)
	TextView mCompanyNameTv;
	@BindView(R.id.local_house_tv)
	TextView mLocalHouseTv;
	@BindView(R.id.living_condition_tv)
	TextView mLivingConditionTv;
	@BindView(R.id.marrage_condition_tv)
	TextView mMarrageConditionTv;
	@BindView(R.id.education_condition_tv)
	TextView mEducationConditionTv;
	@BindView(R.id.customer_manager_code_tv)
	TextView mCustomerManagerCodeTv;
	@BindView(R.id.cma_rcm_ly)
	TableLayout mCmaRcmLy;
	@BindView(R.id.submit_tv)
	TextView mSubmitTv;
	@BindView(R.id.search_progress_history_btn)
	TextView mSearchProgressHistoryBtn;
	@BindView(R.id.calculate_amount_describe_tv)
	TextView mCalculateAmountDescribeTv;
	@BindView(R.id.calculate_ly)
	LinearLayout mCalculateLy;

	private Unbinder mBind;
	private ProgressDetailModel.DetailBean mDetailBean;
	private ProgressDetailPresenter mPresenter;
	private String mRcmdId;
	private List<ProgressDetailModel.History> mHistorys;
	private HistoricalProgressDialog mHistoryDialog;


	public static void start(Activity aty, String rcmdId) {
		Intent intent = new Intent(aty, ProgressDetailActivity.class);
		intent.putExtra(EXTRA_RCMD_ID, rcmdId);
		aty.startActivity(intent);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.progress_detail_activity;
	}

	public int getTopBarBackgroundColor() {
		return getResources().getColor(R.color.color_ffffff);
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setBtnBackVisible(true);
		setupTopBar(R.string.rcm_details, true, false, true, false);
		setTitle(R.string.rcm_details);
		mBind = ButterKnife.bind(this);
		mRcmdId = getIntent().getStringExtra(EXTRA_RCMD_ID);
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);

	}

	@Override
	protected void onStart() {
		super.onStart();
		if(mPresenter != null){
			mPresenter.getDetail(mRcmdId);
		}
	}

	@Override
	public void onRightBtnPressed() {
		super.onRightBtnPressed();
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_D009, mDetailBean.status);
		CheckCreditActivity.start(this, mRcmdId, mDetailBean.creditType);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new ProgressDetailPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		if (mPresenter == null) {
			mPresenter = (ProgressDetailPresenter) data;
			mPresenter.attach(this);
			if(mDetailBean != null) {
				mPresenter.getDetail(mRcmdId);
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getSupportLoaderManager().destroyLoader(LOADER_ID);
		mBind.unbind();
	}

	@Override
	public void pretreatmentAfterSetBaseView() {
	}

	@Override
	public void initContentView() {
	}

	@OnClick({R.id.search_progress_history_btn, R.id.submit_tv, R.id.calculate_amount_btn})
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.search_progress_history_btn:
				StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_D004, mDetailBean.status);
				if (mHistorys == null) {
					mPresenter.getProgressHitstory(mRcmdId);
					return;
				}
				showHistoryDialog();
				break;
			case R.id.submit_tv:
				if (mDetailBean == null) {
					mPresenter.getDetail(mRcmdId);
					return;
				}
				if (TextUtils.equals(mSubmitTv.getText().toString(), getString(R.string.contact_customer))) {
					showCallDialog(mDetailBean.phone);
					StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_D005, mDetailBean.status);
				} else {
					StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_D007);
					SupplementActivity.start(this, mDetailBean);
				}
				break;
			case R.id.calculate_amount_btn:
				StringBuilder builder = new StringBuilder();
				builder.append(mDetailBean.calculatorUrl).append("?rcmdId=").append(mDetailBean.rcmdId);
				WebActivity.start(this, builder.toString(), getString(R.string.try_to_count));
				break;
		}
	}

	@Override
	public void confirmCall() {
		super.confirmCall();
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_D006, mDetailBean.status);
	}

	@Override
	public void onGetDetailSuccess(ProgressDetailModel.DetailBean detail) {
		mDetailBean = detail;
		mStatusTv.setText(mDetailBean.status);
		mTimeTv.setText(mDetailBean.rcmdTime);
		mStatusTipTv.setText(mDetailBean.statusTip);
		mCustomNameTv.setText(mDetailBean.name);
		mApplicantLicenseTv.setText(mDetailBean.certId);
		mCellPhoneNumberTv.setText(mDetailBean.phone);
		if (TextUtils.equals(Constants.COUNT_NOT_NEED_TO_CALCULATE,mDetailBean.isCalculator)) {
			mCalculateLy.setVisibility(View.GONE);
		} else if(TextUtils.equals(Constants.COUNT_HAS_BEEN_CALCULATED,mDetailBean.isCalculator)){
			mCalculateLy.setVisibility(View.VISIBLE);
			mCalculateAmountDescribeTv.setText(getString(R.string.count_tips, mDetailBean.loantype, FormatUtils.getDecoratedAmountWithSymbol(mDetailBean.maxAmount)));
		}else if(TextUtils.equals(Constants.COUNT_HAS_NOT_BEEN_CALCULATED,mDetailBean.isCalculator)){
			mCalculateLy.setVisibility(View.VISIBLE);
			mCalculateAmountDescribeTv.setText(getString(R.string.count_has_not_been_calculated_tips));
		}
		mSearchProgressHistoryBtn.setVisibility(mDetailBean.historyType ? View.VISIBLE : View.GONE);

		//云贷推荐过来的，不显示查看征信按钮，处理按钮内容说明为：联系客户
		if (TextUtils.equals(Constants.RECOMMEND_FROM_LAS, mDetailBean.rcmdType)) {
			mSubmitTv.setText(R.string.contact_customer);
			mCmaRcmLy.setVisibility(View.GONE);
			return;
		}
		//云测推荐
		mCmaRcmLy.setVisibility(View.VISIBLE);
		mResidentialCityTv.setText(mDetailBean.city);
		mTypeOfJobTv.setText(mDetailBean.employeeType);
		mCompanyNameTv.setText(mDetailBean.corpName);
		mLocalHouseTv.setText(mDetailBean.localHouseFlag);
		mLivingConditionTv.setText(mDetailBean.livingCondition);
		mMarrageConditionTv.setText(mDetailBean.marriage);
		mEducationConditionTv.setText(mDetailBean.educationLevel);
		if (!TextUtils.isEmpty(mDetailBean.customerMgr)) {
			mCustomerManagerCodeTv.setText(mDetailBean.customerMgr);
		}
		//是否允许查看征信
		if (!TextUtils.equals(Constants.DO_NOT_CHECK_CREDIT, mDetailBean.creditType)) {
			setBtnRightVisible(true);
			setBtnRightTx(R.string.check_credit_report);
		}
		//是否需要补件
		if (TextUtils.equals(Constants.NO_NEED_SUPPLEMENT, mDetailBean.supplementType)) {
			mSubmitTv.setText(R.string.contact_customer);
		} else {
			mSubmitTv.setText(R.string.immediate_supplementary_information);
		}
	}

	@Override
	public void onGetDetailFailure(String tips) {
		showToast(tips);
	}

	@Override
	public void onGetProgressHistoryFailure(String tips) {
		showToast(tips);
	}

	@Override
	public void onGetProgressHistorySuccess(List<ProgressDetailModel.History> list) {
		mHistorys = list;
		showHistoryDialog();
	}

	private void showHistoryDialog() {
		if (null == mHistoryDialog) {
			mHistoryDialog = new HistoricalProgressDialog(this, new HistoricalProgressAdapter(mHistorys));
		}
		mHistoryDialog.show();
	}

	class HistoricalProgressDialog extends Dialog {

		LinearLayoutManager layoutManager;
		HistoricalProgressAdapter adapter;

		public HistoricalProgressDialog(Context context, HistoricalProgressAdapter baseAdapter) {
			super(context, R.style.progress_style);
			adapter = baseAdapter;
			layoutManager = new LinearLayoutManager(context);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.historical_progress_layout);
			ButterKnife.bind(this);
			RecyclerView view = findViewById(R.id.historical_lv);
			view.setLayoutManager(layoutManager);
			view.setAdapter(adapter);
			Window window = getWindow();
			window.setGravity(Gravity.CENTER);
			setCanceledOnTouchOutside(false);
		}

		@OnClick(R.id.historical_progress)
		public void onClick() {
			dismiss();
		}
	}

}
